package edu.jxufe.nb112.blog.web.controller;

import edu.jxufe.nb112.blog.core.persist.entity.User;
import edu.jxufe.nb112.blog.core.persist.entity.UserAuth;
import edu.jxufe.nb112.blog.core.persist.service.user.UserService;
import edu.jxufe.nb112.common.code.mode.JsonResponse;
import edu.jxufe.nb112.common.web.aop.annotation.UserDataVerify;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lvxi on 2018/1/21.
 * Note:
 */
@Controller
@RequestMapping
public class RegisterController  extends BaseController {

    private final static Logger LOG = LoggerFactory.getLogger(RegisterController.class.getName());
    @Autowired
    UserService userService;

    /**
     * 注册页面
     * @return
     */
    @RequestMapping("register")
    public String registerPage(){
        return "register";
    }

    /**
     * 注册提交
     * @return
     */
    @RequestMapping(value = "register" ,method = RequestMethod.POST)
    @UserDataVerify
    @ResponseBody
    public JsonResponse registerSubmit(@Valid  User user, BindingResult bindingResult,
                                       @RequestParam(value = "password",required = false) String password){


        JsonResponse ret = new JsonResponse(false);
        if(password==null || password.length()<6 || password.length()>30){
            //校验password长度
            ret.setCode("1").setFields(new String[]{"password"});
        }
        else if(userService.hasAccount(user.getAccount())) {
            //校验账号
            ret.setMessage("该账号已经被注册了");
        }else{
            //随机产生32位盐
            RandomStringGenerator randomStringGenerator = new RandomStringGenerator.Builder().withinRange('a','z').build();
            String randSalt = randomStringGenerator.generate(32);

            UserAuth userAuth = new UserAuth();
            userAuth.setSalt(randSalt);
            userAuth.setAccount(user.getAccount());
            //加密密码
            Md5Hash md5Hash = new Md5Hash(password,randSalt,2);
            userAuth.setPassword(md5Hash.toString());

            Boolean status = userService.register(user,userAuth);
            ret.setStatus(status);
            if(!status) {
                ret.setMessage("注册失败");
            }

        }
        return ret;
    }


    /**
     * 登录页面
     * @return
     */
    @RequestMapping("login")
    public String loginPage(){
        return "login";
    }

    /**
     * 登录提交
     * @return
     */
    @RequestMapping(value = "login" ,method = RequestMethod.POST)
    @UserDataVerify
    @ResponseBody
    public JsonResponse loginSubmit(@RequestParam(value = "account") String account, @RequestParam(value = "password") String password,@RequestParam(value = "rememberMe",required = false)Boolean rememberMe,@RequestParam(value = "maxAge",required = false) Integer maxAge){

        JsonResponse ret = new JsonResponse(false);
        if(account.contains("@")){
            //邮箱登录
            account = userService.findAccountByEmail(account);
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        token.setRememberMe(rememberMe==null?false:rememberMe);
        try {
            //token.setRememberMe(true);
            subject.login(token);
            ret.setStatus(true);
        }catch (LockedAccountException e) {
            String msg="账号已被锁定,禁止登录";
            if(StringUtils.isNotEmpty(e.getMessage())){
                msg="账号已被锁定,禁止登录,"+e.getMessage()+"后解锁";
            }
            ret.setMessage(msg);
        }catch (ExcessiveAttemptsException e){
            ret.setMessage("多次登录失败，账号已被锁定,"+e.getMessage()+"后解锁");
        }
        catch (AuthenticationException e) {
            ret.setMessage("用户名密码错误,登录失败");
        }

        return ret;
    }

    /**
     * 退出
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(){
        SecurityUtils.getSubject().logout();
        return redirect("/");
    }

    /**
     * 账号是否存在
     * @param account
     * @return
     */
    @RequestMapping(value = "account/hasAccount")
    public ResponseEntity hasAccount(@RequestParam("account") String account){
        if(StringUtils.isEmpty(account)){
            return ResponseEntity.badRequest().body("");
        }
        boolean isExists = userService.hasAccount(account);
        Map<String,Boolean> ret = new HashMap<String, Boolean>();
        ret.put("status",isExists);
        return ResponseEntity.ok(ret);
    }

    /**
     * 账号是否存在
     * @param email
     * @return
     */
    @RequestMapping(value = "account/hasEmail")
    public ResponseEntity hasEmail(@RequestParam("email") String email){
        if(StringUtils.isEmpty(email)){
            return ResponseEntity.badRequest().body("");
        }
        boolean isExists = userService.hasEmail(email);
        Map<String,Boolean> ret = new HashMap<String, Boolean>();
        ret.put("status",isExists);
        return ResponseEntity.ok(ret);
    }

}
